package com.thundersoft.pickcolor.fragment;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.thundersoft.pickcolor.R;
import com.thundersoft.pickcolor.activity.CollectActivity;
import com.thundersoft.pickcolor.activity.LoginActivity;
import com.thundersoft.pickcolor.activity.ToolActivity;
import com.thundersoft.pickcolor.activity.UserInfoActivity;
import com.thundersoft.pickcolor.database.DatabaseHelper;
import com.thundersoft.pickcolor.utils.L;
import com.thundersoft.pickcolor.utils.ShareUtils;

import java.io.File;
import java.io.FileNotFoundException;

import de.hdodenhof.circleimageview.CircleImageView;

public class FragmentMine extends Fragment {
    private CircleImageView mAvatarCircleImageView;
    private Button mToolBtn, mInfoBtn, mCollectBtn,mLogoutBtn;
    private TextView mUsernameTextView, mAgeTextView, mSexTextView;
    private AlertDialog.Builder avatarDialog;
    private View view;
    String sex = "";
    int age = 0;
    private DatabaseHelper mDatabaseHelper;
    private SQLiteDatabase mSQLiteDatabase;
    private Context mContext;
    private static final int SETAVATAR = 10;
    private static final int INITDIALOGAVATAR = 11;
    private boolean isDeniedPermission = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_mine, null);

        mContext = view.getContext();
        mAvatarCircleImageView = view.findViewById(R.id.user_img);
        mInfoBtn = view.findViewById(R.id.btn_info);
        mToolBtn = view.findViewById(R.id.btn_tool);
        mCollectBtn = view.findViewById(R.id.btn_collect);
        mLogoutBtn = view.findViewById(R.id.btn_logout);

        String avatarName = queryAvatar();

        /**
         * 查询头像文件路径
         * 判断头像路径是否存在
         */
        if(avatarName == null || !isAvatarFileExist(avatarName)){
            mAvatarCircleImageView.setImageResource(R.drawable.pickcolor_icon);
        }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && !isDeniedPermission){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE},SETAVATAR);
        }else if(isDeniedPermission) {
            mAvatarCircleImageView.setImageResource(R.drawable.pickcolor_icon);
        }else {
            setAvatar();
        }

        mAvatarCircleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 判断是否有权限
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA},INITDIALOGAVATAR);
                }else {
                    // 点击修改头像
                    initDialogAvatar();
                }
            }
        });
        mInfoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                startActivity(intent);
            }
        });
        mToolBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ToolActivity.class);
                startActivity(intent);
            }
        });
        mCollectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CollectActivity.class);
                startActivity(intent);
            }
        });
        
        mLogoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.putBoolean(mContext,"isLogin",false);
                ShareUtils.deleShare(mContext,"username");
                ShareUtils.deleShare(mContext,"age");
                ShareUtils.deleShare(mContext,"sex");
                startActivity(new Intent(mContext,LoginActivity.class));
                getActivity().finish();
            }
        });
        return view;
    }

    private void setAvatar() {
        Bitmap bitmap = null;
        String avatarPath = "file:/"+"/"+Environment.getExternalStorageDirectory().getPath()+
                "/"+queryAvatar();
        try {
            bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
                    .openInputStream(Uri.parse(avatarPath)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 设置头像
        if(bitmap != null){
            mAvatarCircleImageView.setImageBitmap(bitmap);
        }
    }

    private boolean isAvatarFileExist(String avatarName) {
        File file = new File(Environment.getExternalStorageDirectory(),avatarName);
        return file.exists();
    }

    private String queryAvatar() {
        mDatabaseHelper = new DatabaseHelper(getContext(), "PickColor.db",
                null, 1);
        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
        String avatarName = null;
        Cursor cursor = null;
        try {
            cursor = mSQLiteDatabase.query("User",null,"name = ?",
                    new String[]{ShareUtils.getString(mContext,"username","")},
                    null,null,null);
            if(cursor.moveToFirst()){
                // 数据库有该用户，不可以修改用户名
                do {
                    avatarName = cursor.getString(cursor.getColumnIndex("avatarName"));
                } while (cursor.moveToNext());
                return avatarName;
            }else {
                // 数据库没有该用户，可以修改用户名
                return avatarName;
            }
        }catch (Exception e){
            return avatarName;
        }finally {
            cursor.close();
        }
    }

    private void initDialogAvatar() {
        final String[] items = { getString(R.string.take_photo_string),getString(R.string.photo_string) };
        avatarDialog = new AlertDialog.Builder(getContext());
        avatarDialog.setTitle(R.string.modify_avatar_string);
        avatarDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(which == 0){
                    toCamera();
                }else if(which == 1){
                    toPicture();
                }
            }
        }).show();
    }


    public static final String PHOTO_IMAGE_FILE_NAME = "fileImg.jpg";
    public static final int CAMERA_REQUEST_COOD = 100;
    public static final int PICTURE_REQUEST_COOD = 101;
    public static final int RESULT_REQUEST_COOD = 102;
    private File tempFile = null;
    private Uri uritempFile;

    // 跳转相机
    private void toCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 判断内存卡是否可用，可用的话就进行存储
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        PHOTO_IMAGE_FILE_NAME)));
        startActivityForResult(intent,CAMERA_REQUEST_COOD);
    }


    // 跳转相册
    private void toPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,PICTURE_REQUEST_COOD);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != getActivity().RESULT_CANCELED){
            switch (requestCode){
                // 相册返回的数据
                case PICTURE_REQUEST_COOD:
                    startPhotoZoom(data.getData());
                    break;

                // 相机返回的数据
                case CAMERA_REQUEST_COOD:
                    tempFile = new File(Environment.getExternalStorageDirectory(),
                            PHOTO_IMAGE_FILE_NAME);
                    startPhotoZoom(Uri.fromFile(tempFile));
                    break;
                case RESULT_REQUEST_COOD:
                    // 有可能点击舍弃
                    if(uritempFile != null){
                        // 拿到图片设置
                        L.d("222:"+uritempFile.toString());
                        saveImageToView(uritempFile);

                        // 既然已经设置了图片，我们原先的就应该删除
                        if(tempFile!=null){
                            tempFile.delete();
                        }
                    }
                    break;
            }
        }
    }

    // 图片裁剪
    private void startPhotoZoom(Uri uri){
        if(uri ==null){
            L.e("uri ==null");
            return;
        }
        L.d("uri !=null");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");

        // 设置裁剪
        intent.putExtra("crop","true");

        // 裁剪宽高比例
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);

        // 裁剪图片的质量/分辨率
        intent.putExtra("outputX",320);
        intent.putExtra("outputY",320);

        uritempFile = Uri.parse("file:/"+"/"+Environment.getExternalStorageDirectory().getPath()+
                "/"+"avatar.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uritempFile);
        intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent,RESULT_REQUEST_COOD);

    }

    // 设置图片
    private void saveImageToView(Uri uritemp){
        if(uritemp !=null){
            Bitmap bitmap = null;
            String avatarName = "avatar.jpg";
            try {
                bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uritemp));

                // 设置头像
                mAvatarCircleImageView.setImageBitmap(bitmap);

                // 保存到数据库
                mDatabaseHelper = new DatabaseHelper(getContext(), "PickColor.db",
                        null, 1);
                mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("avatarName", avatarName);
                mSQLiteDatabase.update("user", values, "name = ?",
                        new String[]{ShareUtils.getString(mContext,"username","")});
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        // 设置用户信息
        setUserInfo(view);
    }

    // 查询数据库sex和age
    private void setUserInfo(View view) {
        mDatabaseHelper = new DatabaseHelper(getContext(), "PickColor.db",
                null, 1);
        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
        Cursor setuser = null;
        String username= ShareUtils.getString(getContext(),"username","");
        setuser = mSQLiteDatabase.query("User", null, "name = ?",
                new String[]{username}, null, null, null);
        if(setuser.moveToFirst()){
            // 数据库有该用户'
            do {
                sex = setuser.getString(setuser.getColumnIndex("sex"));
                age = setuser.getInt(setuser.getColumnIndex("age"));
            } while (setuser.moveToNext());
        }
        mAgeTextView=view.findViewById(R.id.txuage);
        mSexTextView=view.findViewById(R.id.txusex);
        mUsernameTextView=view.findViewById(R.id.tv_username);
        mUsernameTextView.setText(username);
        mSexTextView.setText(sex);
        mAgeTextView.setText(String.valueOf(age));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == SETAVATAR){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                setAvatar();
            }else {
                isDeniedPermission = true;
            }

        }else if(requestCode == INITDIALOGAVATAR){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED){
                // 点击修改头像
                initDialogAvatar();
            }
        }
    }
}








